package com.example.forum.services.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserServices;
import com.example.forum.utils.MD5Utils;
import com.example.forum.utils.UUIDSaltUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * date: 2024/09/07 15:11<br/>
 * Description:对用户的操作
 *
 * @author: jmy <br/>
 */
@Service
@Slf4j
public class UserServicesImpl implements IUserServices {

    @Resource
    private UserMapper userMapper;

    //普通用户注册
    @Override
    public boolean createNormalUser(User user) {
        //1.参数校验
        if (user == null
                || !StringUtils.hasLength(user.getUserName())
                || !StringUtils.hasLength(user.getNickName())
                || !StringUtils.hasLength(user.getPassword())
        ) {
            //日志
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.getMessagesg());
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2.查询用户是否已经存在
        User userExit = userMapper.selectByUserName(user.getUserName());
        if (userExit != null) {
            log.warn(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //3.新增用户信息
        //设置默认值
        User.setUserDefaultValues(user);
        int result = userMapper.insert(user);
        if (result == 0) {
            log.error(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        } else {
            log.info(ResultCode.SUCCESS.toString());
            return true;
        }
    }

    //通过userName查询
    @Override
    public User selectByUserName(String userName) {
        //参数校验
        if (userName == null || userName.trim().equals("")) {
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //查询
        User user = userMapper.selectByUserName(userName);
        if (user == null) {
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.toString());
        }
        return user;
    }

    //登录
    @Override
    public User login(String userName, String password) {
        //参数校验
        if (userName == null || userName.trim().equals("")
                || password == null || password.trim().equals("")
        ) {
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //校验用户是否存在
        User user = userMapper.selectByUserName(userName);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS + "userName:" + userName + "password:" + password);
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.toString());
        }
        //密码校验
        if (!MD5Utils.verify(password, user)) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(ResultCode.FAILED_LOGIN.toString());
        }
        return user;
    }

    @Override
    public User selectById(Long id) {
        //参数校验
        if (id == null) {
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.toString());
        }
        return user;
    }

    @Override
    public Integer addOneArticleCountById(Long userId) {
        if (userId == null || userId <= 0) {
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户
        User user = userMapper.selectByPrimaryKey(userId);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS + "board id ");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //更新用户贴子数
        Integer row = userMapper.addArticleCount(user.getId());
        if (row != 0) {
            return row;
        } else throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
    }

    @Override
    public Integer subOneArticleCountById(Long id) {
        if (id == null || id <= 0) {
            log.error(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS + "board id ");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //判断用户贴子数 是否为0 若本来就为0就不变
        if (user.getArticleCount() == 0) {
            return 1;
        }
        //更新用户发帖数 count-1
        Integer row = userMapper.subArticleCount(user.getId());
        if (row != 0) {
            return row;
        } else throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
    }

    @Override
    public Integer updateByPrimaryKeySelective(User user) {
        //参数校验
        if (user == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //构建跟新对象
        User newUser = userMapper.selectByPrimaryKey(user.getId());
        Integer count = newUser.getArticleCount();
        newUser.setArticleCount(count - 1);
        int result = userMapper.updateByPrimaryKeySelective(newUser);
        if (result != 1) {
            log.warn(ResultCode.FAILED + "board id ");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        return result;
    }

    @Override
    public void modifyInfo(User user) {
        //1.参数校验 user id
        if (user == null || user.getId() == null || user.getId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE + "user:" + user);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.判断用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if (existsUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //3.定义一个标志位
        boolean checkAttr = false;//false 表示没有通过校验

        //4.定义一个专门用来跟新的对象，防止用户传入的User对象设置了其他属性
        //当使用动态sql进行跟新的时候，覆盖没有经过校验的字符串
        User updateUser = new User();


        //5.设置用户id
        updateUser.setId(user.getId());

        //6.对于每一个参数进行非空校验 并赋值
//        //6.1用户名校验
//        if (    !user.getUserName().trim().equals("")
//                && !existsUser.getUserName().equals(user.getUserName())){
//            //需要跟新用户名
//            User checkUser = userMapper.selectByUserName(user.getUserName());
//            if (checkUser != null){
//                //用户已经存在
//                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
//                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
//            }
//            //数据库中没有找到相应的用户表示可以修改  (用户名是唯一标识，不能重复)
//            updateUser.setUserName(user.getUserName());
//            checkAttr = true;
//        }

        //6.2.校验昵称
        if (user.getNickName() != null) {
            //设置昵称
            updateUser.setNickName(user.getNickName());
            //设置标志位
            checkAttr = true;
        }
//        //6.3.校验性别
//        if (user.getGender() != null){
//            //设置性别
//            updateUser.setGender(user.getGender());
//            if (updateUser.getGender() >2 || updateUser.getGender()<0){
//                updateUser.setGender((byte)2);
//            }
//            checkAttr = true;
//        }
        //6.4.校验邮箱
        if (user.getEmail() != null) {
            //设置邮箱
            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }
        //6.5.校验电话号码
        if (user.getPhoneNum() != null) {
            //设置电话号码
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }
        //6.6.校验个人简介
        if (user.getRemark() != null) {
            //设置电话号码
            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }
        //7.根据标志位 判断是否跟新
        if (!checkAttr) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //8.调用mapper
        int result = userMapper.updateByPrimaryKeySelective(updateUser);
        if (result == 0) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public Integer modifyPassword(Long id, String newPassword, String oldPassword) {
        //1.参数校验
        if (id == null || id <= 0 ||
                newPassword == null || newPassword.trim().equals("") ||
                oldPassword == null || oldPassword.trim().equals("")
        ) {
            log.warn(ResultCode.FAILED_PASSWORD_NOT_NUM.toString());
            throw new ApplicationException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        //2.查询用户信息 校验用户是否存在
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1) {
            log.error(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.toString());
        }

        //3.1 输入的 旧密码加盐
        String oldPasswordSalt = MD5Utils.md5Salt(oldPassword, user.getSalt());

        //3.2 判断 旧密文是否与 输入的旧密码生成的密文相等
        if (!oldPasswordSalt.equalsIgnoreCase(user.getPassword())) {
            log.warn(ResultCode.FAILED_PASSWORD_ERROR.toString());
            throw new ApplicationException(ResultCode.FAILED_PASSWORD_ERROR.toString());
        }
        //4.给新密码加盐
        String salt = UUIDSaltUtils.uuidSalt_32();
        String newPasswordSalt = MD5Utils.md5Salt(newPassword, salt);

        //构造要更新的对象
        User updateUser = new User();
        updateUser.setPassword(newPasswordSalt);
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setUpdateTime(new Date());

        //调用mapper 动态更新
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row == 0) {
            log.warn(ResultCode.FAILED.toString());
            throw new ApplicationException(ResultCode.FAILED.toString());
        }
        return row;
    }

}
